// routes/commentRoutes.js
const express = require('express');
const router = express.Router();
const commentModel = require('../controllers/commentControll');
const { expressjwt: expressJwt } = require('express-jwt');
const key = "Yangjunjwt123456"; // 秘钥
// 获取博客的所有评论
router.get('/blog/:blogId', async (req, res) => {
  try {
    const comments = await commentModel.getCommentsByBlogId(req.params.blogId);
    res.json(comments);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});
// 添加评论
router.post('/add', expressJwt({ secret: key, algorithms: ['HS256'] }), async (req, res) => {
  try {
    const { blog_id, content } = req.body;
    const { userId  } = req.auth; // 从 JWT 中获取用户信息

    const commentId = await commentModel.createComment(blog_id, userId, content);
    const newComment = await commentModel.getCommentsByBlogId(blog_id);
      //  const newComment = await commentModel.getCommentsByBlogId(commentId);
    res.status(201).json(newComment);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});
// 删除评论
// router.delete('/:id', async (req, res) => {
//   try {
//     await commentModel.deleteComment(req.params.id);
//     res.json({ message: 'Comment deleted successfully' });
//   } catch (error) {
//     res.status(500).json({ message: error.message });
//   }
// });
router.delete('/:comment_id', expressJwt({ secret: key, algorithms: ['HS256'] }), async (req, res) => {
  try {
    const { comment_id } = req.params;
    await commentModel.deleteComment(comment_id);
    res.status(200).json({ message: '评论已删除' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});
// 回复评论

router.post('/reply', expressJwt({ secret: key, algorithms: ['HS256'] }), async (req, res) => {
  try {
    const { comment_id, content } = req.body;
    const { userId } = req.auth; // 从 JWT 中获取用户信息

    const blog_id = await commentModel.getBlogIdByCommentId(comment_id); // 获取原评论的 blog_id
    if (!blog_id) {
      return res.status(404).json({ message: 'Comment not found' });
    }

    const replyId = await commentModel.replyComment(blog_id, userId,  content, comment_id);
    const updatedComments = await commentModel.getCommentsByBlogId(blog_id);
    res.status(201).json(updatedComments);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});
module.exports = router;

